package com.ouc.yyi.config.shiro;



import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ouc.yyi.config.model.SysUser;
import com.ouc.yyi.system.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private SysUserService sysUserService;
    /**
     * 授权的时候使用
     * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //从session中获取到用户
        SysUser sysUser = (SysUser)principals.fromRealm(this.getClass().getName()).iterator().next();
        //获得到角色信息
        //Set<Role> roleSet = sysUser.getRoles();
        Integer roleId = sysUser.getRoleId();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole(roleId.toString());
        return simpleAuthorizationInfo;
    }
    /**
     * 认证登陆时候使用
     * */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        //User user = userService.getUserByUserName(username);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("username",username);
        SysUser sysUser = sysUserService.selectOne(wrapper);
        if(sysUser==null){
            throw new UnknownAccountException("没有找到该用户");
        }else{
            return new SimpleAuthenticationInfo(sysUser,sysUser.getPassword(),this.getClass().getName());
        }


    }
}
